<?php

/**
 * import ( "ORG.Net.HttpFile" );
 * @author Mark_Code
 *
 */
class HttpFile
{

    public static function GetImgHost ($Random = true)
    {
        $Img_HOST = C("IMG_SEVER_HOST");
        if (is_array($Img_HOST)) {
            return ($Img_HOST[array_rand($Img_HOST)]);
        }
        return $Img_HOST;
    }

    /**
     * 
     * 由本地发起连接
     * 
     * @param 本地地址 $localPath
     * @param 类型,普通img,商品pic,人物Ap $types
     * @param 是否强制缩略图 $isEnforce
     */
    public static function sendLocal ($localPath, $extension = "jpg", $types = "img", 
    $isEnforce = false)
    {
        $HTTP_URL = "http://" . HttpFile::GetImgHost() . "/server.php?" . http_build_query(
        array("t" => $types, "enforce" => ($isEnforce ? 1 : 0), 
        "ext" => $extension));
        $datas = fopen($localPath, 'r');
        $process = curl_init();
        curl_setopt($process, CURLOPT_URL, $HTTP_URL);
        $headers = array('Expect:');
        if (is_resource($datas)) {
            fseek($datas, 0, SEEK_END);
            $length = ftell($datas);
            fseek($datas, 0);
            $headers[] = 'Content-Length: ' . $length;
            curl_setopt($process, CURLOPT_INFILE, $datas);
            curl_setopt($process, CURLOPT_INFILESIZE, $length);
        }
        curl_setopt($process, CURLOPT_POST, 1);
        curl_setopt($process, CURLOPT_CUSTOMREQUEST, "POST");
        $date = gmdate('D, d M Y H:i:s \G\M\T');
        
        $headers[] = "Date: {$date}";
        $headers[] = 'Authorization: ';
        $headers[] = 'Content-Type: ';
        
        curl_setopt($process, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($process, CURLOPT_HEADER, 0);
        curl_setopt($process, CURLOPT_TIMEOUT, 300);
        curl_setopt($process, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($process, CURLOPT_FOLLOWLOCATION, 1);
        $r = curl_exec($process);
        // 				$rc = curl_getinfo ( $process, CURLINFO_HTTP_CODE );
        // 				$r_offset = curl_getinfo ( $process, CURLINFO_HEADER_SIZE );
        curl_close($process);
        fclose($datas);
        return json_decode($r);
    }

    /**
     * 有远程发起连接，请确保是否有权限，连接远程服务器
     * 
     * @param 网络地址 $localPath
     * @param 类型,普通img,商品pic,人物Ap $types
     * @param 是否强制缩略图 $isEnforce
     */
    public static function sendlUrl ($urlpath, $types = "img", $isEnforce = false)
    {
        $host = HttpFile::GetImgHost();
        $HTTP_URL = "http://" . $host . "/server.php?" . http_build_query(
        array("t" => $types, "path" => (string) $urlpath, 
        "enforce" => ($isEnforce ? 1 : 0)));

        return json_decode(file_get_contents($HTTP_URL));
    }

}

?>